package com.cn.appcore.http.interceptor

import com.cn.appcore.http.constant.HttpConstant
import com.cn.appcore.utils.ApkUtil
import com.cn.appcore.utils.DecryptUtils
import com.cn.appcore.utils.Preference
import okhttp3.HttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.Interceptor
import okhttp3.Response

/**
 * @author chenxz
 * @date 2018/9/26
 * @desc HeaderInterceptor: 设置请求头
 */
class HeaderInterceptor : Interceptor {

    /**
     * token
     */
    private var userRid: String by Preference(HttpConstant.USER_RID, "")
    private var userId: String by Preference(HttpConstant.USER_ID, "")
    private var channel: String by Preference(HttpConstant.APP_CHANNER, "")


    private val admin = "admin"
    private val merchant = "merchant"

    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        var oldHttpUrl=request.url
        val builder = request.newBuilder()
        val time =System.currentTimeMillis()
//        val time ="1713760845357"
        val sin= DecryptUtils.setSign(time.toString())
        builder.addHeader("Content-type", "application/json; charset=utf-8")
        builder.addHeader("channel","guanfang")
        builder.addHeader("version", ApkUtil.getVersionName())
        builder.addHeader("logintype", HttpConstant.APP_TYPE)
        builder.addHeader("appid", HttpConstant.APP_ID)
        builder.addHeader("timestamp", time.toString())
        builder.addHeader("sign", sin)
//            .removeHeader("User-Agent")
//            .addHeader("User-Agent", ApkUtil.getUserAgent().toString())
        // .header("token", token)
        // .method(request.method(), request.body())
        userId.let {
            if (it.isNotEmpty()) {
//                builder.addHeader("Authorization", token)
                builder.addHeader("uid", userId)
                builder.addHeader("rid", userRid)
            }
        }
        val domain = request.url.host

        if (domain.isNotEmpty()) {
            val spDomain: String by Preference(domain, "")
            val cookie: String = if (spDomain.isNotEmpty()) spDomain else ""
            if (cookie.isNotEmpty()) {
                // 将 Cookie 添加到请求头
//                builder.addHeader(HttpConstant.COOKIE_NAME, cookie)
            }
        }
        return chain.proceed(builder.build())
    }

}